package com.henme.crm.web.admin;

import com.google.common.collect.Lists;
import com.henme.crm.entity.admin.Role;
import com.henme.crm.entity.admin.User;
import com.henme.crm.service.admin.RoleService;
import com.henme.crm.service.admin.UserService;
import com.henme.crm.util.dwz.AjaxDone;
import com.henme.crm.util.dwz.RestultString;
import com.henme.crm.util.page.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;



    @Autowired
    private RoleService roleService;

    @Value("#{settings['upload.dir']}")
    private String uploadDir;

    /**
     * page 获得从页面传过来的分页信息
     *
     * @param page
     * @param model
     * @return
     */
    @RequiresPermissions("user:view")
    @RequestMapping("/list")
    public String list(
            @ModelAttribute("page") Page<User> page,
            @ModelAttribute("user") User user,
            @RequestParam(value = "navtabid", required = false) String navtabid,
            Model model) {
        page.setT(user);
        page = userService.getUserList(page);
        model.addAttribute("page", page);
        model.addAttribute("user", user);
        model.addAttribute("navtabid", navtabid);
        return "user/list";
    }

    /**
     * 编辑页面
     *
     * @param model
     * @param id
     * @param navtabid
     * @return
     */
    @RequiresPermissions("user:edit")
    @RequestMapping(value = "/edit/{id}")
    public String prepare(Model model, @PathVariable("id") Long id,
                          @RequestParam("navtabid") String navtabid) {
        model.addAttribute("navtabid", navtabid);
        model.addAttribute("user", userService.selectUser(id));
        return "user/edit";
    }

    /**
     * 保存更新
     *
     * @param user
     * @param navtabid
     * @return
     */
    @RequiresPermissions("user:edit")
    @ResponseBody
    @RequestMapping("/update")
    public AjaxDone update(@ModelAttribute("user") User user,
                           @RequestParam("navtabid") String navtabid) {
        userService.updateUser(user);
        AjaxDone a = new AjaxDone();
        a.setStatusCode("200");
        a.setCallbackType("closeCurrent");
        a.setMessage("更新成功");
        a.setNavTabId(navtabid); // 重新加载这个nav
        return a;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @RequiresPermissions("user:delete")
    @ResponseBody
    @RequestMapping("/delete/{id}")
    public AjaxDone delete(@PathVariable("id") Long id) {
        userService.deleteUser(id);
        AjaxDone a = new AjaxDone();
        a.setStatusCode("200");
        a.setMessage("删除成功");
        return a;
    }

    /**
     * 锁定帐号
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/locked/{id}")
    public AjaxDone locked(@PathVariable("id") Long id) {
        userService.markLockedbyUserid(id);
        AjaxDone a = new AjaxDone();
        a.setStatusCode("200");
        a.setMessage("锁定帐号成功");
        return a;
    }

    /**
     * 锁定帐号
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/notlocked/{id}")
    public AjaxDone notlocked(@PathVariable("id") Long id) {
        userService.markNotLockedbyUserid(id);
        AjaxDone a = new AjaxDone();
        a.setStatusCode("200");
        a.setMessage("解锁帐号成功");
        return a;
    }

    /**
     * 新增页面
     *
     * @param model
     * @param navtabid
     * @return
     */
    @RequiresPermissions("user:add")
    @RequestMapping("/add")
    public String add(Model model, @RequestParam("navtabid") String navtabid) {
        model.addAttribute("navtabid", navtabid);
        return "user/edit";
    }

    /**
     * 保存新增
     *
     * @param user
     * @param navtabid
     * @return
     */
    @RequiresPermissions("user:add")
    @ResponseBody
    @RequestMapping("/insert")
    public String insert(
            @ModelAttribute("user") User user,
            @RequestParam(value = "clientFile", required = false) MultipartFile clientFile,
            @RequestParam("navtabid") String navtabid) {
        try {
            String fileName = UUID.randomUUID().toString().substring(0, 8);
            String oldFileName = clientFile.getOriginalFilename();
            fileName = fileName
                    + oldFileName.substring(oldFileName.lastIndexOf("."));
            File targetFile = new File(uploadDir, fileName);
            // 保存文件，返回文件名
            clientFile.transferTo(targetFile);
            user.setPicUrl(fileName);
            userService.insertUser(user);
            return RestultString.jsonString("200", "新增成功", navtabid,
                    "closeCurrent", "");
        } catch (IOException e) {
            e.printStackTrace();
            return RestultString.jsonString("300", "新增失败", navtabid,
                    "closeCurrent", "");
        }
    }

    @RequiresPermissions("user:changepassword")
    @ResponseBody
    @RequestMapping("/changepassword/{id}")
    public AjaxDone changepassword(@PathVariable("id") Long id) {
        User u = userService.selectUser(id);
        String newPassword = UUID.randomUUID().toString().substring(0, 8);// 取前8位
        u.setPassword(newPassword);
        userService.updateUser(u);
      //  mailService.sendNotificationMail(u.getUsername(), newPassword,u.getEmail());
        AjaxDone a = new AjaxDone();
        a.setStatusCode("200");
        a.setMessage(u.getUsername() + "用户更新密码邮件发送成功");
        return a;
    }

    @RequiresPermissions("user:userrole")
    @RequestMapping("/role/{userid}")
    public String userrole(@PathVariable("userid") Long userid, Model model) {
        List<Role> list = roleService.getRoleList();
        List<Role> list1 = roleService.getRoleListByuserid(userid);
        List<Role> result = Lists.newArrayList();
        for (Role r : list) {
            for (Role r1 : list1) {
                if (r.getId().equals(r1.getId())) {
                    r.setChecked(true);
                    continue;
                }
            }
            result.add(r);
        }
        model.addAttribute("list", result);
        model.addAttribute("userid", userid);
        return "user/userrole";
    }

    @RequiresPermissions("user:userrole")
    @ResponseBody
    @RequestMapping("/saveuserrole/{userid}")
    public AjaxDone saveuserrole(@PathVariable("userid") Long userid,
                                 @RequestParam("navtabid") String navtabid,
                                 HttpServletRequest request) {
        String[] roleids = request.getParameterValues("roleids");
        userService.saveUserRole(userid, roleids);
        AjaxDone a = new AjaxDone();
        a.setStatusCode("200");
        a.setCallbackType("closeCurrent");
        a.setMessage("更新成功");
        a.setForwardUrl("");
        return a;
    }

    @RequestMapping("/getpic/{userid}")
    public ModelAndView handleRequest(HttpServletRequest request,
                                      HttpServletResponse response, @PathVariable("userid") Long userid)
            throws Exception {
        // Set to expire far in the past.
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control",
                "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");

        // return a jpeg
        response.setContentType("image/jpeg");

        User u = userService.selectUser(userid);
        if(StringUtils.isEmpty(u.getPicUrl())) {
            return null;
        }
        BufferedImage bi = ImageIO.read(new FileInputStream(uploadDir
                + u.getPicUrl()));
        ServletOutputStream out = response.getOutputStream();

        // write the data out
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }

        return null;
    }
}
